<template>
  <!--下拉、分组和tree-->
  <el-select
    v-model="value"
    v-bind="$attrs"
    :id="'c' + meta.columnId"
    :name="'c' + meta.columnId"
    :clearable="clearable"
    :multiple="multiple"
    :collapse-tags="collapseTags"
    :collapse-tags-tooltip="collapseTagsTooltip"
  >
    <!--下拉分组的单选和多选-->
    <template
      v-if="meta.controlType === EControlType.selectGroup || meta.controlType === EControlType.selectGroups"
    >
      <el-option-group
        v-for="group in optionList"
        :key="group.label"
        :label="group.label"
      >
        <el-option
          v-for="item in group.options"
          :key="item.value"
          :label="'　' + item.label"
          :value="item.value"
          :disabled="item.disabled"
        >
        </el-option>
      </el-option-group>
    </template>
    <!--下拉和 tree-->
    <template v-else>
      <el-option
        v-for="item in optionList"
        :key="'select' + item.value"
        :label="optionLabel(item)"
        :value="item.value"
        :disabled="item.disabled"
      >
      </el-option>
    </template>
  </el-select>
</template>

<script setup lang="ts" generic="T extends object">
  import { computed } from 'vue'
  // 组件的 props 接口定义
  import type { IFormChildProps } from '../map'
  // 控制类
  import { itemController, loadController, EControlType } from '../map'
  
  defineOptions({
    name: 'nf-el-from-select',
    inheritAttrs: false,
  })
  
  // 定义 props
  const props = withDefaults(defineProps<IFormChildProps<T> & {
    collapseTags?: boolean,
    collapseTagsTooltip?: boolean
  }>(), {
    meta: () => {
      return {
        colName: '',
        controlType: EControlType.select
      } 
    },
    model: () => {
      return {} as T
    },
    optionList: () => {
      return []
    },
    clearable: true,
    collapseTags: true, // 多选
    collapseTagsTooltip: true
  })

  // 支持防抖等功能
  const { value  } = itemController(props)

  // 区分单选和多选
  const multiple = computed (() => 
    props.meta.controlType === EControlType.selects ||
    props.meta.controlType === EControlType.selectTrees ||
    props.meta.controlType === EControlType.selectGroups
  )

  // label 的 处理，正常和 tree
  const optionLabel = (item) => {
    if (props.meta.controlType === EControlType.selectTree ||
        props.meta.controlType === EControlType.selectTrees
      ){
        return '　'.repeat(item.level) + item.label
      } else {
        return item.label
      }
  }

  // 从后端获取数据
  const { loadDict } = loadController(props)
  loadDict()

</script>